<?php
namespace Admin\Controller;
use Think\Controller;
class UserVoucherController extends Controller {

    private $modelName = 'User_voucher_config';

    public function index(){
        $this->display();
    }

    public function tolist() {
        $page_size = $_POST['page_size'];
        $page_num = $_POST['page_num'];
        // $modelObj = M($this->modelName);
        // $list = $model->page($page_num, $page_size)->select();//page两个参数（页码，条数），不需要自己计算

        $model = M();
        $field = "a.id, a.money, a.voucher_num, a.day_num, b.name,b.use_money, b.name as type, b.remark, GROUP_CONCAT(distinct c.game_name) as voucher_range, count(a.id) totals, count(distinct c.id) ptotals";
        $list = $model->table('fs_user_voucher_config a')
            ->join('left join fs_voucher_type b on b.id = a.type')
            ->join('left join fs_game_type c on FIND_IN_SET(c.id , a.voucher_range)')
            ->field($field)
            ->group('a.id')
            // ->order('end_date,datetime desc')
            ->page($page_num, $page_size)
            ->select();

        $total = $model->table('fs_user_voucher_config')->count('id');

        $data = pageHelper($page_size, $page_num, $list, $total);
        $this->ajaxReturn($data);
    }

    public function addoreditbigtradeconfig(){
        $modelObj = M($this->modelName);
        $data = $modelObj->create($_POST);
        $voucher_range = "0";
        if (!empty($_POST['voucher_range'])) {
            $voucher_range_list = $_POST['voucher_range'];
            $game_model = M("Game_type");
            $total = $game_model->where(array("state"=>1))->count('id');
            if ($total > count($voucher_range_list)) {
                $voucher_range = implode(',',$voucher_range_list);
            }
        }
        $data['voucher_range'] = $voucher_range;
        if ($_POST["id"] > 0) {
            $modelObj->save($data);
            $id = $_POST["id"];
        } else {
            $id = $modelObj->add($data);
        }
        $ajaxdata['code'] = 0;
        $ajaxdata['msg'] = '代金卷配置保存成功';
        $ajaxdata['id'] = $id;
        $this->ajaxReturn($ajaxdata);
    }

    public function get_data() {
        $modelObj = M($this->modelName);
        $data = $modelObj->where(array('id' => $_POST['id']))->find();
        $ajaxdata['data'] = $data;
        $this->ajaxReturn($ajaxdata);
    }

    public function delete() {
        $modelObj = M($this->modelName);
        $map['id'] = $_POST['id'];
        $modelObj->where($map)->delete();
        $data['code'] = 0;
        $this->ajaxReturn($data);
    }
}